#ifndef __M_ONLINE_H__
#define __M_ONLINE_H__
#include <unordered_map>
#include "util.hpp"

class online_manager
{
private:
    // 用于建立游戏大厅用户id和连接的关系
    std::unordered_map<uint64_t, wsserver_t::connection_ptr> _hall_user;
    // 用于建立游戏房间用户id和连接的关系
    std::unordered_map<uint64_t, wsserver_t::connection_ptr> _room_user;
    std::mutex _mutex;
public:
    online_manager() { DLOG("在线管理模块初始化完毕！"); }
    // 连接建立时才会加入游戏大厅&房间在线用户管理
    void enter_game_hall(uint64_t uid, wsserver_t::connection_ptr& con)
    {
        std::unique_lock<std::mutex> _mutex;
        _hall_user.insert(std::make_pair(uid, con));
    }

    void enter_game_room(uint64_t uid, wsserver_t::connection_ptr& con)
    {
        std::unique_lock<std::mutex> _mutex;
        _room_user.insert(std::make_pair(uid, con));
    }

    // 连接断开时才会移除在线用户管理
    void exit_game_hall(uint64_t uid)
    {
        std::unique_lock<std::mutex> _mutex;
        _hall_user.erase(uid);
    }

    void exit_game_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> _mutex;
        _room_user.erase(uid);
    }

    // 判断当前指定用户是否在游戏大厅/游戏房间
    bool is_in_game_hall(uint64_t uid)
    {
        std::unique_lock<std::mutex> _mutex;
        auto it = _hall_user.find(uid);
        if (it == _hall_user.end())
        {
            return false;
        }

        return true;
    }

    bool is_in_game_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> _mutex;
        auto it = _room_user.find(uid);
        if (it == _room_user.end())
        {
            return false;
        }

        return true;
    }

    // 通过用户id获取大厅/房间用户管理对应连接
    wsserver_t::connection_ptr get_con_from_hall(uint64_t uid)
    {
        std::unique_lock<std::mutex> _mutex;
        auto it = _hall_user.find(uid);
        if (it == _hall_user.end())
        {
            return wsserver_t::connection_ptr();
        }

        return it->second;
    }

    wsserver_t::connection_ptr get_con_from_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> _mutex;
        auto it = _room_user.find(uid);
        if (it == _room_user.end())
        {
            return wsserver_t::connection_ptr();
        }

        return it->second;
    }
};

#endif